package com.salmon.study;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedAbstractActor;
import akka.pattern.Patterns;
import lombok.extern.slf4j.Slf4j;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;

@Slf4j
public class WorkActor extends UntypedAbstractActor {

    @Override
    public void onReceive(Object message) throws Throwable {
        log.info("收到的消息:" + message);
        log.info("{}",this.sender().path());
        // 获取发送者， 并发送消息
        this.sender().tell("zzzzz", this.self());
        log.info("{}",this.self().path());
        getContext().stop(this.self());
    }

    @Override
    public void preStart() {
        System.out.println("Father preStart uid=" + getSelf().path().uid() + ", path=" + getSelf().path() + ", object hash=" + this.hashCode());
    }

    @Override
    public void postStop() {
        System.out.println("Father stopped uid=" + getSelf().path().uid() + ", path=" + getSelf().path() + ", object hash=" + this.hashCode());
    }

    public static void main(String[] args) throws Exception {
        ActorSystem system = ActorSystem.create("worker");

        ActorRef workerActor = system.actorOf(Props.create(WorkActor.class),"my-workerActor");

        Future<Object> future = Patterns.ask(workerActor, "这个是我发送的消息我是:" +  workerActor.path(), 1000);

        String a = (String)Await.result(future, Duration.create(2, TimeUnit.SECONDS));

        log.info("收到的消息是：{}", a);

        System.out.println(">>> Press ENTER to exit <<<");
        try {
            System.in.read();
        } finally {
            system.terminate();
        }
    }
}
